package com.elean.pms.common;

import com.elean.pms.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 切面规则 处理权限
 * @author
 *
 */
@Aspect
@Component
public class AuthorizationInterceptor{
	private static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);

	@Autowired
	RedisUtil redisUtils;
	
	//定义切面
	@Pointcut("@annotation(com.elean.pms.common.Authorization)")
	public void annotationPointCut() {}
	
	//定义方法拦截的规则
	@Around("annotationPointCut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(Global.AUTHORIZE_TOKEN);
        logger.debug("切面中获取token："+token);
        if(StringUtils.isEmpty(token)){
        	return ResponseEntity.buildCodes(StatusCode.UNAUTHORIZED, CommonErrorCodes.UNAUTHORIZED);
        }
    	Object obj = redisUtils.get(token);
    	if(obj==null){
        	return ResponseEntity.buildCodes(StatusCode.UNAUTHORIZED, CommonErrorCodes.UNAUTHORIZED);
    	}
		logger.debug("AuthorizationInterceptor passed!");
		Object o = joinPoint.proceed();
		redisUtils.expire(token,Global.TOKEN_EXPIRE); //刷新token时间
        return o;
	}

}
